﻿using eslib.FileManageLib;
using eslib.tools.config;
using NLog;

namespace ArticleClientLib
{
    /// <summary>
    /// 分类
    /// </summary>
    public class Classifly
    {
        Logger logger = LogManager.GetCurrentClassLogger();
        void Info(string msg) => logger.Info(msg);
        void Error(string msg) => logger.Error(msg);


        /// <summary>
        /// 分类id，也是分类目录名称
        /// </summary>
        public long classiflyId { get; set; }


        /// <summary>
        /// 根目录
        /// </summary>
        public string Root { get; set; }

        public Classifly(long classiflyId, string root)
        {
            this.classiflyId = classiflyId;
            Root = root;
        }



        /// <summary>
        /// 软文（动态读取）
        /// </summary>
        public List<LocalArticle> Articles
        {
            get
            {
                List<LocalArticle> list = new();

                string[] dirs = Directory.GetDirectories(Root);
                foreach (var dir in dirs)
                    list.Add(new LocalArticle(dir));

                return list;
            }
        }


        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        public (bool pass, string log) Check()
        {
            bool pass = true;
            string log = "";

            foreach (var article in Articles)
            {
                var res = article.Check();
                if (!res.pass)
                {
                    pass = false;
                    log += res.log;
                }
            }

            return (pass, log);
        }



        #region 数据处理

        /// <summary>
        /// 添加软文（添加目录）
        /// </summary>
        /// <param name="article"></param>
        public void Add(LocalArticle article)
        {
            //先创建目录
            string path = Path.Combine(Root, $"{article.ArticleId}");
            DirCopier.CreateDir(path);

            //复制数据 
            DirCopier.DirectoryCopy(article.Dir, path);

            Articles.Add(new LocalArticle(path));
        }


        /// <summary>
        /// 新建本地软文（添加目录），以UUID为新目录名
        /// </summary>
        /// <param name="template"></param>
        public void AddNew(LocalArticle template)
        {
            //先创建目录
            string path = Path.Combine(Root, $"{Guid.NewGuid().ToString()}");
            DirCopier.CreateDir(path);

            //复制数据 
            DirCopier.DirectoryCopy(template.Dir, path);

            Articles.Add(new LocalArticle(path));
        }


        /// <summary>
        /// 移除软文（整个目录删除）
        /// </summary>
        /// <param name="article"></param>
        public void Remove(LocalArticle article)
        {
            //删除目录
            string[] files = Directory.GetFiles(article.Dir);
            foreach (var file in files) File.Delete(file);

            string imgPath = Path.Combine(article.Dir, "images");
            string[] imgs = Directory.GetFiles(imgPath);
            foreach (var img in imgs) File.Delete(img);

            Directory.Delete(imgPath);
            Directory.Delete(article.Dir);


            //从列表移除
            Articles.Remove(article);
        }


        /// <summary>
        /// 移除本分类下所有软文（慎重）
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        public void RemoveAll()
        {
            foreach (var art in Articles)
            {
                try
                {
                    Info($"移除本地软文[{art.Dir}]");
                    Remove(art);
                }
                catch (Exception ex)
                {
                    Error(ex.Message);
                }
            }
        }
        #endregion



        #region classifly json
        internal static readonly string JsonName = "classifly.json";

        public ClassiflyJson ReadJson()
        {
            return GenericJsonConfig.Load<ClassiflyJson>(Path.Combine(Root, JsonName));
        }

        #endregion
    }
}
